package com.jinduplan.planmanager.ui.activity.project

import android.app.Dialog
import android.text.Editable
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.EditorInfo
import android.widget.EditText
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.cxz.kotlin.baselibs.adapter.CustomRecyclerAdapter
import com.cxz.kotlin.baselibs.adapter.ViewHolder
import com.cxz.kotlin.baselibs.base.BaseMvpActivity
import com.cxz.kotlin.baselibs.utils.GsonHelper
import com.cxz.kotlin.baselibs.utils.UserInfoUtil
import com.fphoenixcorneae.util.toast.ToastUtil
import com.jinduplan.planmanager.R
import com.jinduplan.planmanager.bean.*
import com.jinduplan.planmanager.mvp.contract.ProjectContract
import com.jinduplan.planmanager.mvp.contract.ProjectDetailContract
import com.jinduplan.planmanager.mvp.presenter.ProjectDetailPresenter
import com.jinduplan.planmanager.mvp.presenter.ProjectPresenter
import com.jinduplan.planmanager.utils.CustomRecyclerFilterableAdapter
import com.jinduplan.planmanager.utils.ResUtil
import kotlinx.android.synthetic.main.activity_project.*
import kotlinx.android.synthetic.main.activity_project.back
import kotlinx.android.synthetic.main.activity_project.recyclerView
import kotlinx.android.synthetic.main.activity_project_detail.*
import kotlinx.android.synthetic.main.activity_project_detail.tv_basketNum
import kotlinx.android.synthetic.main.activity_project_detail.tv_surface
import kotlinx.android.synthetic.main.activity_project_upload_detail.*
import java.util.HashSet


class ProjectDetailActivity :
    BaseMvpActivity<ProjectContract.View, ProjectContract.Presenter>(), ProjectContract.View {
    private var typeDialog: Dialog? = null

    override fun createPresenter(): ProjectContract.Presenter = ProjectPresenter()

    private var projectBeanList: ArrayList<DataProjectBean.DataBean>? = null
    private var buildingBeanList: ArrayList<DataProjectBean.DataBean.BuildingBean>? = null
    private var facadeBeanList: ArrayList<DataProjectBean.DataBean.FacadeBean>? = null
    private var labourBeanList: ArrayList<DataProjectBean.DataBean.LabourBean>? = null
    private var hangingBlueBeanList: ArrayList<DataProjectBean.DataBean.HangingBlueBean>? = null
    private var projectList: ArrayList<DataProjectBean.DataBean.ProjectBean>? = null
    private var constructionList: ArrayList<DataProjectBean.DataBean>? = null
    private var project_id: Int = 0
    private var facade_id: Int = 0
    private var labour_id: Int = 0
    private var hangingblue_id: Int = 0
    private var building_id: Int = 0
    private var msg_stauts: Int = 0
    private var msgData: MessageBean.DataBean? = null
    private var audit_id: Int = 0

    override fun start() {
        projectBeanList = ArrayList()
        buildingBeanList = ArrayList()
        facadeBeanList = ArrayList()
        hangingBlueBeanList = ArrayList()
        constructionList = ArrayList()
        labourBeanList = ArrayList()


        recyclerView.adapter =
            object : CustomRecyclerAdapter<DataProjectBean.DataBean.BuildingBean>(
                this, R.layout.item_project_sign, buildingBeanList
            ) {
                override fun convert(
                    holder: ViewHolder?,
                    t: DataProjectBean.DataBean.BuildingBean?,
                    position: Int
                ) {
                    var buildingName = holder?.getView<TextView>(R.id.tv_name)
                    buildingName?.text = t?.building_name
                    buildingName?.isSelected = t?.isSelect == true
                    holder?.convertView?.setOnClickListener {
                        for (i in 0 until buildingBeanList!!.size) {
                            buildingBeanList!![i].isSelect = false
                        }
                        buildingBeanList!![position].isSelect = true
                        recyclerView.adapter?.notifyDataSetChanged()
                        building_id = t?.id!!.toInt()
                        constructionList?.clear()
                        constructionList?.addAll(
                            getConstructionDetail(
                                facade_id,
                                hangingblue_id,
                                building_id,
                                labour_id
                            )
                        )
                        recyclerView_detail.adapter?.notifyDataSetChanged()
                    }

                }

            }
        recyclerView.layoutManager = LinearLayoutManager(this)

        recyclerView_detail.adapter =
            object : CustomRecyclerAdapter<DataProjectBean.DataBean>(
                this, R.layout.item_project_detail, constructionList
            ) {
                override fun convert(
                    holder: ViewHolder?,
                    t: DataProjectBean.DataBean?,
                    position: Int
                ) {
                    holder?.setText(R.id.tv_construction, t?.workmanship?.workmanship_name)
                    holder?.setText(
                        R.id.tv_construction_process,
                        t?.construction?.construction_process
                    )
                    holder?.setText(R.id.tv_area, t?.completion_area.toString())

                }

            }
        recyclerView_detail.layoutManager = LinearLayoutManager(this)

        var labourArray=ArrayList<Labour>()
        labourArray.addAll(GsonHelper.parseArray(UserInfoUtil.labour_json,Labour::class.java))
        var labour_id=0
        for (i in 0 until labourArray!!.size) {
            if(labourArray[i].project_id.toInt()==project_id){
                labour_id=labourArray[i].id
            }
        }
        mPresenter?.getProjectList(1, 500, project_id, audit_id,0,0)
    }

    private fun getConstructionDetail(
        facade_id: Int,
        hangingblue_id: Int,
        building_id: Int,
        labour_id: Int
    ): ArrayList<DataProjectBean.DataBean> {
        var construction = ArrayList<DataProjectBean.DataBean>()
        for (i in 0 until projectBeanList!!.size) {
            if (facade_id == projectBeanList!!.get(i).facade_id && building_id == projectBeanList!!.get(
                    i
                ).building_id &&
                hangingblue_id == projectBeanList!!.get(i).hanging_blue_id
//                && labour_id==projectBeanList!!.get(i).labour_id
            ) {
                construction.add(projectBeanList!![i])
            }
        }
        if (construction.size == 0) {
            tv_no_data.visibility = View.VISIBLE
            recyclerView_detail.visibility = View.GONE
        } else {
            tv_no_data.visibility = View.GONE
            recyclerView_detail.visibility = View.VISIBLE
        }
        setBtStatus(construction[0].audit)
        return construction

    }

    override fun initView() {
        super.initView()
        setStatusBarColor(ResUtil.getC(R.color.white))
        tv_title.text = intent.getStringExtra("project_name")
        project_id = intent.getIntExtra("project_id", 0)
        if (null != intent.getIntExtra("audit_id", 0)) {
            audit_id = intent.getIntExtra("audit_id", 0)
        }
        //从消息列表进来
        if (null != intent.getSerializableExtra("msg")) {
            msgData = intent.getSerializableExtra("msg") as MessageBean.DataBean?
            var projectBean = GsonHelper.parse(msgData?.data, MsgProjctBean::class.java)
            audit_id = projectBean.audit_id
            mPresenter?.readMessage(msgData!!.id, 1)
            bt_reject.setOnClickListener {
                mPresenter?.auditMsg(projectBean.audit_id, 2)
            }
            bt_config.setOnClickListener {
                mPresenter?.auditMsg(projectBean.audit_id, 1)
            }
        }
        ivBack.setOnClickListener { finish() }
        ll_surface.setOnClickListener {
            showTypeDialog(1)
        }
        ll_basket.setOnClickListener {
            showTypeDialog(2)
        }
        llPerson.setOnClickListener {
            showTypeDialog(3)
        }
    }

    override fun attachLayoutRes(): Int {
        return R.layout.activity_project_detail
    }

    private fun showTypeDialog(type: Int) {
        typeDialog = Dialog(this, R.style.BottomDialog)
        val contentView: View =
            LayoutInflater.from(this).inflate(R.layout.dialog_project_upload_detail, null)
        typeDialog!!.setContentView(contentView)
        val layoutParams: ViewGroup.LayoutParams = contentView.layoutParams
        layoutParams.width = resources.displayMetrics.widthPixels
        contentView.layoutParams = layoutParams
        typeDialog!!.setCanceledOnTouchOutside(true)

        typeDialog!!.window?.setGravity(Gravity.BOTTOM)
        typeDialog!!.window?.setWindowAnimations(R.style.BottomDialog_Animation)
        typeDialog!!.show()
        var projectList = ArrayList<Any>()
        projectList.clear()
        // //1 立面选择 2 吊篮选择
        when (type) {
            1 -> {
                typeDialog!!.findViewById<TextView>(R.id.tv_type).text = "立面选择"
                projectList.addAll(facadeBeanList!!)
                if (projectList.size > 0) {
                    for (i in 0 until projectList.size) {
                        (projectList[i] as DataProjectBean.DataBean.FacadeBean).isSelect = false
                    }
                    (projectList[0] as DataProjectBean.DataBean.FacadeBean).isSelect = true
                    tv_surface.text =
                        (projectList[0] as DataProjectBean.DataBean.FacadeBean).facade_name
                }
            }
            2 -> {
                typeDialog!!.findViewById<TextView>(R.id.tv_type).text = "吊篮选择"
                projectList.addAll(hangingBlueBeanList!!)
                if (projectList.size > 0) {
                    for (i in 0 until projectList.size) {
                        (projectList[i] as DataProjectBean.DataBean.HangingBlueBean).isSelect =
                            false
                    }
                    (projectList[0] as DataProjectBean.DataBean.HangingBlueBean).isSelect = true
                    tv_basketNum.text =
                        (projectList[0] as DataProjectBean.DataBean.HangingBlueBean).hanging_blue_name
                }
            }
            3 -> {
                typeDialog!!.findViewById<TextView>(R.id.tv_type).text = "人员选择"
                projectList.addAll(labourBeanList!!)
                if (projectList.size > 0) {
                    for (i in 0 until projectList.size) {
                        (projectList[i] as DataProjectBean.DataBean.LabourBean).isSelect = false
                    }
                    (projectList[0] as DataProjectBean.DataBean.LabourBean).isSelect = true
                    tvPerson.text =
                        (projectList[0] as DataProjectBean.DataBean.LabourBean).full_name
                }
            }
        }
        typeDialog!!.findViewById<ImageView>(R.id.iv_close)
            .setOnClickListener {
                constructionList?.clear()
                constructionList?.addAll(
                    getConstructionDetail(
                        facade_id,
                        hangingblue_id,
                        building_id,
                        labour_id
                    )
                )
                recyclerView_detail.adapter?.notifyDataSetChanged()
                typeDialog!!.dismiss()
            }


        val recyclerView = typeDialog!!.findViewById<RecyclerView>(R.id.recyclerView)
//        typeDialog!!.findViewById<EditText>(R.id.ed_search).addTextChangedListener(object :
//            android.text.TextWatcher {
//            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
//            }
//
//            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
//                (recyclerView.adapter as CustomRecyclerFilterableAdapter<Any>).filter.filter(s.toString())
//            }
//
//            override fun afterTextChanged(s: Editable?) {
//            }
//        })


        recyclerView.adapter = object : CustomRecyclerFilterableAdapter<Any>(
            this, R.layout.item_rv_choose, projectList
        ) {
            override fun convert(holder: ViewHolder?, t: Any?, position: Int) {
                //1 立面选择 2 吊篮选择
                when (type) {
                    1 -> {
                        t as DataProjectBean.DataBean.FacadeBean
                        val textName = holder?.getView<TextView>(R.id.tv_name)
                        textName?.text = t?.facade_name
                        textName?.isSelected = t?.isSelect == true
                        holder?.setVisible(R.id.iv_choose, t?.isSelect == true)
                        holder?.convertView?.setOnClickListener {
                            var projects = ArrayList<Any>()
                            projects.clear()
                            projects.addAll((recyclerView.adapter as CustomRecyclerFilterableAdapter<Any>).data)
                            for (index in 0 until projectList.size) {
                                (projects!![index] as DataProjectBean.DataBean.FacadeBean).isSelect =
                                    false
                            }
                            (projects!![position] as DataProjectBean.DataBean.FacadeBean).isSelect =
                                true
                            facade_id =
                                (projects!![position] as DataProjectBean.DataBean.FacadeBean).id
                            tv_surface.text =
                                (projects!![position] as DataProjectBean.DataBean.FacadeBean).facade_name
                            recyclerView.adapter?.notifyDataSetChanged()
                        }
                    }
                    2 -> {
                        t as DataProjectBean.DataBean.HangingBlueBean
                        val textName = holder?.getView<TextView>(R.id.tv_name)
                        textName?.text = t?.hanging_blue_name
                        textName?.isSelected = t?.isSelect == true
                        holder?.setVisible(R.id.iv_choose, t?.isSelect == true)
                        holder?.convertView?.setOnClickListener {
                            var projects = ArrayList<Any>()
                            projects.clear()
                            projects.addAll((recyclerView.adapter as CustomRecyclerFilterableAdapter<Any>).data)
                            for (index in 0 until projects.size) {
                                (projects!![index] as DataProjectBean.DataBean.HangingBlueBean).isSelect =
                                    false
                            }
                            (projects!![position] as DataProjectBean.DataBean.HangingBlueBean).isSelect =
                                true
                            hangingblue_id =
                                (projects!![position] as DataProjectBean.DataBean.HangingBlueBean).id
                            tv_basketNum.text =
                                (projects!![position] as DataProjectBean.DataBean.HangingBlueBean).hanging_blue_name
                            recyclerView.adapter?.notifyDataSetChanged()
                        }
                    }
                    3 -> {
                        t as DataProjectBean.DataBean.LabourBean
                        val textName = holder?.getView<TextView>(R.id.tv_name)
                        textName?.text = t?.full_name
                        textName?.isSelected = t?.isSelect == true
                        holder?.setVisible(R.id.iv_choose, t?.isSelect == true)
                        holder?.convertView?.setOnClickListener {
                            var projects = ArrayList<Any>()
                            projects.clear()
                            projects.addAll((recyclerView.adapter as CustomRecyclerFilterableAdapter<Any>).data)
                            for (index in 0 until projects.size) {
                                (projects!![index] as DataProjectBean.DataBean.LabourBean).isSelect =
                                    false
                            }
                            (projects!![position] as DataProjectBean.DataBean.LabourBean).isSelect =
                                true
                            labour_id =
                                (projects!![position] as DataProjectBean.DataBean.LabourBean).id
                            tvPerson.text =
                                (projects!![position] as DataProjectBean.DataBean.LabourBean).full_name
                            recyclerView.adapter?.notifyDataSetChanged()
                        }
                    }
                }
            }
        }
        recyclerView.layoutManager = LinearLayoutManager(this)
    }

    override fun setProjectListData(projectData: DataProjectBean) {
        projectBeanList!!.clear()
        projectBeanList!!.addAll(projectData.data)
        if (projectBeanList!!.size == 0) return

        for (index in 0 until projectBeanList!!.size) {
            buildingBeanList?.add(projectBeanList!![index].building)
            facadeBeanList?.add(projectBeanList!![index].facade)
            hangingBlueBeanList?.add(projectBeanList!![index].hanging_blue)
            labourBeanList?.add(projectBeanList!![index].labour)
        }
        removeListDuplicate(buildingBeanList as ArrayList<Any>)
        removeListDuplicate(facadeBeanList as ArrayList<Any>)
        removeListDuplicate(hangingBlueBeanList as ArrayList<Any>)
        removeListDuplicate(labourBeanList as ArrayList<Any>)
        tv_surface.text = facadeBeanList!![0].facade_name
        tv_basketNum.text = hangingBlueBeanList!![0].hanging_blue_name
        if(labourBeanList!!.size>0){
            if (null != labourBeanList!![0]) {
                tvPerson.text = labourBeanList!![0].full_name
            }
        }
        facade_id = projectBeanList!![0].facade_id
        hangingblue_id = projectBeanList!![0].hanging_blue_id
        building_id = projectBeanList!![0].building_id
        labour_id = projectBeanList!![0].labour_id
        buildingBeanList!![0].isSelect = true
        facadeBeanList!![0].isSelect = true
        hangingBlueBeanList!![0].isSelect = true
        if (null != labourBeanList!![0]) {
            labourBeanList!![0].isSelect = true
        }
        constructionList?.clear()
        constructionList?.addAll(
            getConstructionDetail(
                facade_id,
                hangingblue_id,
                building_id,
                labour_id
            )
        )
        recyclerView_detail.adapter?.notifyDataSetChanged()
        recyclerView.adapter?.notifyDataSetChanged()
        setBtStatus(projectData.data[0].audit)
    }

    private fun setBtStatus(audit: DataProjectBean.DataBean.AuditBean) {
        if (null != intent.getSerializableExtra("msg")) {
            msgData = intent.getSerializableExtra("msg") as MessageBean.DataBean?
            var projectBean = GsonHelper.parse(msgData?.data, MsgProjctBean::class.java)
            ll_bt.visibility = View.VISIBLE
            //审核状态 0 待审核 1 审核通过 2 审核驳回
            msg_stauts = audit.status
            if (msg_stauts == 0) {
                bt_reject.visibility = View.VISIBLE
                bt_config.visibility = View.VISIBLE
                bt_unstaging.visibility = View.GONE
            } else if (msg_stauts == 1) {
                bt_reject.visibility = View.GONE
                bt_config.visibility = View.GONE
                bt_unstaging.visibility = View.GONE
                ll_bt.visibility = View.GONE
            } else {
                bt_reject.visibility = View.GONE
                bt_config.visibility = View.GONE
                bt_unstaging.visibility = View.VISIBLE
            }
        }
    }


    override fun readMsgSuccess() {

    }

    override fun auditMsgSuccess() {
        ToastUtil.show("操作成功")
        finish()
    }

    //去重
    private fun removeListDuplicate(list: ArrayList<Any>): ArrayList<Any> {
        val h = HashSet(list)
        list.clear()
        list.addAll(h)
        return list
    }
}